import React, { Component } from 'react';
import ThePagination from "@/components/ThePagination";
import { Form, Input, Select, Space, message, Button, DatePicker, Modal, Tooltip, TreeSelect } from "antd";
import { SearchOutlined, MinusCircleOutlined, PlusOutlined, TagsOutlined, QuestionCircleOutlined } from "@ant-design/icons";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import { apiGetDBAreaList } from "@/request/callServicer/serveList";
import { apiStockLibraryManageAdd, apiGetAllProprietaryStore, apiGetAllProprietaryStorePage, apiStockLibraryManagePage, apiGetLibraryByStoreId, apiStockLibraryManageList, apiStockLibraryManageView, apiSetUpLibraryAreaMatching, apiGetLibraryAreaMatching, apiSysUserList, apiStockLibraryManageDel, apiStockLibraryManageEdit } from '@/request/storageManager/store.js'
import TheQueryForm from '@/components/TheQueryForm';
import TheTableExtend from '@/components/TheTableExtend'
import store from "@/store/store"
import DndSort from './components/dndSort'
const { Option } = Select
export default class OutPut extends Component {
    constructor() {
        super()
        this.formRef = React.createRef()
        this.dndSortRef = React.createRef()
        this.queryFormRef = React.createRef()

        this.state = {
            checkedArea: [],
            isModalVisible: false,
            columns: [
                {
                    title: "店铺名称",
                    dataIndex: "storeName",
                    key: "merchantName",
                    render: (text, render) => {
                        return text
                    }
                },
                {
                    title: "拥有仓库",
                    dataIndex: "libraryName",
                    key: "libraryName",
                    render: (text, render) => {
                        return text
                    }
                },

                {
                    title: "操作",
                    dataIndex: "serviceShowFile",
                    key: "serviceShowFile",
                    render: (text, render) => {
                        return <div>
                            <TheButton haspermi={['storage:store:storeEdit']} onClick={() => this.onArea(render)}>地区匹配  </TheButton>
                            <TheButton haspermi={['storage:store:storeEdit']} onClick={() => this.onPriority(render)}> 仓库优先级  </TheButton>
                        </div>
                    }
                },
            ],
            dataSource: [],
            pageData: {
                pageNo: 1,
                pageSize: 10

            },
            total: 0,
            modalTitle: '仓库匹配策略',
            searchOption: [
                { field: 'libraryName', label: '仓库名称/编码', placeholder: '仓库名称/编码', required: false, rules: [], type: 'Input', defaultValue: '' },
                { field: 'storeName', label: '商家名称', placeholder: '商家名称', required: false, rules: [], type: 'Input', defaultValue: '' },

            ],
            queryForm: {},
            dbArea: [],
            areaMatching: [],
            libraryOfStore: [],
            filteredDbArea: []
        }
    }
    componentDidMount() {
        this.getData()
        this.getDbArea()
    }

    getDbArea() {
        apiGetDBAreaList().then(res => {
            if (res.code === 0) {
                const data = res.data.filter(item => {
                    if (item.level == 0 || item.level == 1) {
                        return item
                    }
                }).map(item => item.areaName)

                this.setState({
                    dbArea: data,
                    filteredDbArea: data,
                })
            }
        })
    }

    getData(values) {
        let { pageNo, pageSize } = this.state.pageData
        this.setState({
            queryForm: values === undefined ? this.state.queryForm : { ...values }
        }, async () => {
            let res = await apiGetAllProprietaryStorePage({
                pageNo: this.state.pageData.pageNo,
                pageSize: this.state.pageData.pageSize,
                ...this.state.queryForm
            })
            if (res.code === 0) {
                this.setState({
                    dataSource: res.data,
                    total: res.totalCount
                })
            }
        })

    }
    onPriority(row) {
        apiGetLibraryByStoreId({ storeId: row.storeId }).then(res => {
            if (res.code === 0) {
                this.setState({
                    libraryOfStore: res.data.map((item, index) => {
                        return {
                            ...item,
                            key: index + 1,

                        }
                    }),
                }, () => {
                    this.dndSortRef.current.open(this.state.libraryOfStore, row.storeId)
                })
            }
        })
    }

    async onArea(row) {
        // 
        apiGetLibraryByStoreId({ storeId: row.storeId }).then(res => {
            if (res.code === 0) {
                // 获取匹配
                apiGetLibraryAreaMatching({ storeId: row.storeId }).then(res2 => {
                    if (res2.code == 0) {
                        this.setState({
                            libraryOfStore: res.data,
                            isModalVisible: row.storeId,
                            areaMatching: res2.data
                        }, () => {
                            const sights = this.state.areaMatching.map(item => {
                                return {
                                    area: item.matchingRegion.split(','),
                                    storeID: item.libraryId
                                }
                            })
                            this.refreshCheckData(sights)
                            this.formRef.current.setFieldsValue({
                                sights: sights
                            })
                        })
                    }
                })

            }
        })

    }
    async onFinish(values) {
        console.log(values);
        const { sights } = values
        const apply = {
            libraryAreaMatchingS: sights.map(item => {
                return {
                    "libraryId": item.storeID,
                    "matchingRegion": item.area.join(','),
                    "storeId": this.state.isModalVisible,
                }
            }),
            "storeId": this.state.isModalVisible,

        }
        apiSetUpLibraryAreaMatching(apply).then(res => {
            if (res.code === 0) {
                message.success(res.codeMessage)
                this.setState({
                    isModalVisible: false,
                    checkedArea: [],
                    filteredDbArea: this.state.dbArea
                })
            }
        })
    }

    reset() {
        this.formRef.current.setFieldsValue({
            sights: []
        })
        this.setState({
            libraryOfStore: null,
            isModalVisible: '',
            areaMatching: null
        })
    }

    pageChange = (pageNo, pageSize) => {
        this.setState({
            pageData: {
                pageNo, pageSize
            }
        }, () => {
            this.getData()
        })
    };
    onCancel() {
        this.reset()
        this.setState({ isModalVisible: false })
    }
    onReset() {
        this.setState({
            queryForm: {}
        }, () => {
            this.pageChange(1, 10)
        })
    }

    onFormSearch(values) {
        this.setState({
            pageData: { pageNo: 1, pageSize: 10 }
        }, () => {
            this.getData(values)
        })
    }
    onAreaDeselect(e, index) {
        const { sights } = this.formRef.current.getFieldsValue()
        console.log(sights, index);

        const checkData = []
        sights.forEach(item => {
            if (item) {
                const { area } = item
                if (area) {
                    checkData.push(...area)
                }
            }


        })


        this.setState({
            checkedArea: checkData,
            filteredDbArea: this.state.dbArea.filter(item => !checkData.includes(item))
        })
    }
    onAreaChange(e, index) {
        const { sights } = this.formRef.current.getFieldsValue()
        console.log(sights[index]);
        if (e == '全国') {
            const owner = sights[index].area
            sights[index].area = Array.from(new Set(sights[index].area.concat(...this.state.filteredDbArea.map(item => item))))
            sights[index].area.splice(sights[index].area.indexOf('全国'), 1)
            this.formRef.current.setFieldsValue({
                sights
            })
            const checkedArea = this.state.dbArea.map(item => item)
            console.log(checkedArea, 'checkedArea');
            this.setState({
                checkedArea: checkedArea,
                filteredDbArea: []
            }, () => {
                console.log(this.state.checkedArea, this.state.checkedArea.splice(checkedArea.indexOf('全国'), 1));
                this.setState({
                    checkedArea: this.state.checkedArea.splice(checkedArea.indexOf('全国'), 1)
                })
            })
        } else {
            const { checkedArea } = this.state
            checkedArea.push(e)
            this.setState({
                checkedArea,
                filteredDbArea: checkedArea.length === this.state.dbArea.length - 1 ? [] : this.state.dbArea.filter(item => !checkedArea.includes(item))
            })
        }

    }
    onStoreChange(e) {
        const { sights } = this.formRef.current.getFieldsValue()
        const storeIdCheck = []
        sights.forEach(item => {
            if (item && item.storeID) {
                storeIdCheck.push(item.storeID)
            }
        })
        this.setState({
            libraryOfStore: this.state.libraryOfStore.map(item => {
                if (storeIdCheck.includes(item.id)) {
                    item.disabled = true
                } else {
                    item.disabled = false
                }
                return item
            })
        })
    }

    OnRemove(index) {
        const { sights } = this.formRef.current.getFieldsValue()
        this.refreshCheckData(sights)

    }
    refreshCheckData(sights) {
        const storeIdCheck = []
        const checkedArea = []
        sights.forEach(item => {
            if (item) {
                const { area, storeID } = item
                if (area) {
                    checkedArea.push(...area)
                }
                if (storeID) {
                    storeIdCheck.push(storeID)
                }
            }
        })
        this.setState({
            checkedArea,
            filteredDbArea: checkedArea.length === this.state.dbArea.length - 1 ? [] : this.state.dbArea.filter(item => !checkedArea.includes(item)),
            libraryOfStore: this.state.libraryOfStore.map(item => {
                if (storeIdCheck.includes(item.id)) {
                    item.disabled = true
                } else {
                    item.disabled = false
                }
                return item
            }),

        })
    }
    render() {
        let { libraryOfStore, isModalVisible, columns, dataSource, modalTitle, pageData, total, searchOption, filteredDbArea } = this.state
        const text = `
        仓库匹配策略
        新订单将基于收货地址所在的区域，根据地区匹配策
        略去适配仓库。
        若地区匹配策略匹配失败，则根据仓库优先级来匹配
        仓库，若单一仓库无法履约，则会进行拆单。`
        return (
            <div className="p-layout-box commodity-examine">
                <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={true} option={searchOption}
                    onGetValues={(values) => this.onFormSearch(values)}
                    onReset={(values) => this.onReset(values)}
                >
                </TheQueryForm>
                <TheTable
                    scroll={{ x: "max-content", y: '63vh' }}
                    columns={columns}
                    dataSource={dataSource}
                />
                <ThePagination
                    pageNo={pageData.pageNo}
                    pageSize={pageData.pageSize}
                    total={total}
                    pageChange={this.pageChange}
                />
                <Modal title={
                    <Tooltip title={text}>
                        地区匹配策略<QuestionCircleOutlined />
                    </Tooltip>
                } visible={isModalVisible} width="700px"
                    onCancel={() => this.onCancel()} footer={null}
                >
                    {
                        isModalVisible && <Form

                            ref={this.formRef}
                            onFinish={(values) => this.onFinish(values)}

                        >

                            <Form.List name="sights">
                                {(fields, { add, remove }) => (
                                    <>
                                        {fields.map((field, index) => (
                                            <Space key={field.key + "key"} align="baseline" style={{ width: '100%' }}>

                                                <Form.Item
                                                    {...field}
                                                    label="区域"
                                                    name={[field.name, 'area']}
                                                    rules={[
                                                        {
                                                            required: true,
                                                            message: '请选择区域',
                                                        },
                                                    ]}
                                                >
                                                    <Select
                                                        style={{
                                                            width: 200,
                                                        }}
                                                        mode="multiple"
                                                        onSelect={(e) => this.onAreaChange(e, index)}
                                                        onDeselect={(e) => this.onAreaDeselect(e, index)}
                                                        options={filteredDbArea.map((item) => ({
                                                            value: item,
                                                            label: item,
                                                        }))}
                                                    >

                                                    </Select>
                                                    {/* <TreeSelect treeData={dbArea}
                                                        onChange={(e,) => this.onTreeChange(e)}
                                                        treeCheckable={true}
                                                        style={{ width: '800px' }}></TreeSelect> */}
                                                </Form.Item>
                                                <Form.Item
                                                    {...field}
                                                    label="仓库"
                                                    name={[field.name, 'storeID']}
                                                    rules={[
                                                        {
                                                            required: true,
                                                            message: '请选择仓库',
                                                        },
                                                    ]}

                                                >
                                                    <Select
                                                        style={{
                                                            width: 200,
                                                        }}
                                                        allowClear
                                                        onChange={(e) => this.onStoreChange(e)}
                                                    >
                                                        {libraryOfStore.map((item) => (
                                                            <Option key={item.id} value={item.id} disabled={item.disabled}>
                                                                {item.name}
                                                            </Option>
                                                        ))}
                                                    </Select>
                                                </Form.Item>
                                                <MinusCircleOutlined style={{ marginLeft: 50 }} onClick={() => {
                                                    remove(field.name)
                                                    this.OnRemove(index)
                                                }} />
                                            </Space>
                                        ))}
                                        {
                                            fields.length < libraryOfStore.length && <Form.Item >
                                                <Button type="primary" onClick={() => add()} block icon={<PlusOutlined />} style={{ marginLeft: 40, width: '50%', }}>
                                                    新 增
                                                </Button>
                                            </Form.Item>
                                        }
                                    </>
                                )}
                            </Form.List>
                            <Form.Item wrapperCol={{
                                offset: 8,
                                span: 16,
                            }}>
                                <Space size="small" style={{ marginLeft: 10 }}>

                                    <Button type="default" onClick={() => this.reset()}>
                                        取消
                                    </Button>
                                    <Button type="primary" htmlType="submit">
                                        确定
                                    </Button>
                                </Space>
                            </Form.Item>
                        </Form>
                    }
                </Modal>
                <DndSort ref={this.dndSortRef}></DndSort>
            </div >
        );
    }
}
